<template>
  <el-tree
    v-loading="loading"
    ref="tree"
    :data="jsonTree"
    default-expand-all
    style="margin-top: 12px;"
    show-checkbox
    node-key="id"
    highlight-current
    @node-click="nodeClickHandle" />
</template>

<script>
import { getJsonTree } from '@/utils/index'
import {
  getAppMenu
} from '@/api/admin/auth/gms/roleManage'
export default {
  name: 'AppMenuTree',
  props: {
    dataType: Number,
    menuCategory: {
      type: Number,
      default: 0
    },
    data: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      tree: []
    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text))
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    }
  },
  mounted() {
    this.searchTree()
  },
  methods: {
    // 加载树
    searchTree() {
      this.loading = true
      getAppMenu(this.dataType, this.menuCategory)
        .then(res => {
          debugger
          this.loading = false
          this.deleteRes(res.treejson)
          this.tree = res.treejson
          console.log(res.treejson)
          this.$refs['tree'].setCheckedKeys(this.data)
        })
        .catch(err => {
          this.loading = false
        })
    },
    // 删除无效数据(无父节点)
    deleteRes(res) {
      const result = []
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        const pid = res[i].parent
        const oid = res[i].id
        result[oid] = pid
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent === '#') continue
        if (res[j] && result[res[j].parent] === null) {
          const index = j
          j = 0
          delete result[res[index].id]
          res.splice(index, 1)
        }
      }
    },
    // 树点击
    nodeClickHandle(data) {
      const {
        text
      } = data
      this.text = text
    },
    getSelectTreeNode() {
      const selectedHalfNode = this.$refs['tree'].getCheckedKeys() // 父节点
      const selectedNode = this.$refs['tree'].getHalfCheckedKeys() // 子节点
      const allNode = selectedHalfNode.concat(selectedNode)
      // 去掉一级菜单
      for (let k = 0; k < allNode.length; k++) {
        const nodekv = allNode[k]
        if (nodekv.length === 2) {
          allNode.splice(k, 1)
        }
      }
      return allNode
    }
    // 分配权限保存

  }
}
</script>

<style scoped>

</style>
